<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\model\integral\Order;
use app\common\model\MoneyLog;
use app\common\model\order\Order as OrderOrder;
use app\common\model\ScoreLog;
use app\common\model\User as ModelUser;
use app\common\model\user\Withdrawal;
use fast\Random;
use think\Config;
use think\Db;
use think\Log;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'miniLogin','score_log'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $user = $this->auth->getUser();
        $user['my_team'] = ModelUser::where('pid', $user['id'])->count();
        //我的邀请人
        $user['my_inviter'] = ModelUser::where('id', $user['pid'])->value('nickname');
        //推广权益
        $user['promotion_interest'] = config('site.promotion_interest');
        //总佣金
        $user['total_commission'] = MoneyLog::where('source_type', 503)->where('user_id',$user['id'])->sum('money');
        $this->success('', $user);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *@ApiInternal
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *@ApiInternal
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiInternal
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        // $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        // $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        // if ($username) {
        //     $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
        //     if ($exists) {
        //         $this->error(__('Username already exists'));
        //     }
        //     $user->username = $username;
        // }
        if ($nickname) {
            // $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            // if ($exists) {
            //     $this->error(__('Nickname already exists'));
            // }
            $user->nickname = $nickname;
        }
        // $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *@ApiInternal
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *@ApiInternal
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }



    /**
     * 重置密码
     *@ApiInternal
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @Author LK
     * @ApiTitle (微信小程序登录)
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="integer", required=true, sample="", description="登录code")
     * @ApiParams (name="phoneCode", type="string", required=true, sample="", description="手机code")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function miniLogin()
    {
        $params = $this->request->param();
        extract($params);

        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            if (!$decryptSession || !isset($decryptSession['openid'])) {
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            // 分参
            // $decrypt = $wechat->getAccessToken();
            // $token = $decrypt['access_token'];
            $res = $wechat->getPhone($phoneCode);
            if ($res['errcode'] == 0) {
                $phone = $res['phone_info'];
            } else {
                exception('失败:' . $res['errmsg']);
            }
            $user = \app\common\model\User::get([
                'openid'   => $decryptSession['openid']
            ]);

            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                $user->save();
                // 直接登陆
                $result = $this->auth->direct($user->id);
            } else {
                // 写入个人数据
                if (isset($pid) && !empty($pid)) {
                    $decryptSession['pid'] = $pid;
                }
                $decryptSession['phoneNumber'] = $phone['phoneNumber'];
                $decryptSession['nickname'] = $nickname ?? '微信用户';
                // 写入个人数据
                $result = $this->auth->oauthRegister($decryptSession);
            }
            if (!$result) {
                exception('授权登录失败了!' . $this->auth->getError());
            }
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            $this->error($e->getMessage());
        }
        $this->success('授权登录成功', $this->auth->getUserInfo());
    }
    /**
     * @Author LK
     * @ApiTitle (积分明细)
     * @ApiMethod (get)
     * @ApiParams (name="type", type="string", required=true, sample="", description="1=收入,2=支出")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function score_log()
    {
        $param = request()->param();
        extract($param);
        $list = ScoreLog::where('type', $type)->where('user_id', $this->auth->id)->order('id desc')->paginate();
        foreach ($list as $v) {
            $v->orderList = Order::get(['sn' => $v->order_sn], ['ordergoods']);
            $v->orderLists = OrderOrder::get(['sn' => $v->order_sn], ['ordergoods']);
        }
        $this->success('', $list);
    }

    /**
     * @Author LK
     * @ApiTitle (提现)
     * @ApiMethod (POST)
     * @ApiParams (name="money", type="integer", required=true, sample="", description="提现金额")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawal()
    {
        $post = $this->request->post();
        $user = $this->auth->getUser();
        $post['user_money'] = $user['money'];
        extract($post);
        $validate = validate('user.Withdrawal'); //使用助手函数
    
        $result = $validate->scene('wechat')->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        if ($user['money'] < $money) {
            $this->error('余额不足');
        }
        $withdrawal_commission = config('site.withdrawal_commission');
        if ($withdrawal_commission > 0 && $withdrawal_commission <= 100) {
            $withdrawal_commission_fee = bcdiv($withdrawal_commission, 100, 2);
            $handling_charge = bcmul($money, $withdrawal_commission_fee, 2);
        } else {
            $handling_charge = 0;
        }
        $post['sn'] = sn('user_withdrawal', 'sn', 'TX');
        $post['user_id'] = $user['id'];
        $post['handling_charge'] = $handling_charge;
        $post['amount_received'] = bcsub($money, $handling_charge, 0);
        $post['type'] = 1;
        Db::startTrans();
        try {
            $tx = new Withdrawal($post);
            $tx->allowField(true)->save();
            MoneyLog::income($user['id'], $money, 2, 501, $post['sn']);
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('申请成功');
    }
    /**
     * @Author LK
     * @ApiTitle (用户提现记录)
     * @ApiMethod (get)
     * @ApiParams (name="state", type="integer", required=true, sample="", description="1=提现中,2=提现成功,3=提现失败")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawalLog()
    {
        $get = request()->get();
        extract($get);
        $withdrawal = new Withdrawal;
        if ($state != 'all') {
            $withdrawal->where('state', $state);
        }
        $withdrawal->where('user_id', $this->auth->id);
        $withdrawal->order('createtime desc');
        $list = $withdrawal->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d') as create_time")->paginate(10);
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @ApiTitle (我的团队)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function my_team()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;
        $user = new ModelUser();
        $user->where('pid', $uid);
        $lists = $user->paginate();
        foreach ($lists as $v) {
            $v->generate_commission = MoneyLog::where('user_id', $uid)->where('uid', $v->id)->sum('money');
        }
        $this->success('', $lists);
    }

    /**
     * @Author LK
     * @ApiTitle (推广订单)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function commission_log()
    {
        $lists = MoneyLog::with(['user'])->where('user_id', $this->auth->id)->where('source_type', 503)->where('type', '1')->order('id desc')->paginate();
        foreach ($lists as $v) {
            $v->info = OrderOrder::get(['sn' => $v->order_sn], ['ordergoods', 'user']);
        }
        $this->success('', $lists);
    }
}
